<template>
  <div>
    <v-chart class="chart" :option="option" />
    <!--  -->
    <el-table id="scalingTable" :data="scaleList" style="width: 100%" :stripe="true">
      <el-table-column type="expand" fixed>
        <template slot-scope="props">
          <el-table :data="props.row.strategyList" class="strategy-table-expand">
            <el-table-column label="弹性规则" prop="rule" min-width="40%" />
            <el-table-column label="伸缩条件" prop="metricCond" min-width="30%" />
            <el-table-column label="伸缩资源" prop="optNum" min-width="10%" />
            <el-table-column label="午高峰最大值" prop="metricValue" min-width="15%" />
            <el-table-column label="状态" prop="state" min-width="5%" />
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="服务Appkey" prop="appkey" min-width="20%" />
      <el-table-column label="SET分组" prop="cell" min-width="15%" />
      <el-table-column label="有效" prop="status" min-width="5%" />
      <el-table-column label="无效原因" prop="description" min-width="10%" />
      <el-table-column label="流量分组" prop="groupInfo" min-width="25%" />
      <el-table-column label="资源占比" prop="groupQuota" min-width="5%" />
      <el-table-column label="操作" min-width="5%">
        <template slot-scope="line">
          <el-button size="mini" @click="gotoHulk(line.row.appkey)">去配置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: center;margin-top: 30px;">
      <el-pagination :page-size="pageSize" background layout="prev, pager, next" :total="total"
        @current-change="doPagination">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { GridComponent } from 'echarts/components';
import { BarChart } from "echarts/charts";
import {
  ToolboxComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from "echarts/components";
import VChart from "vue-echarts";
import axios from 'axios';
// 超时时间
axios.defaults.timeout = 10 * 1000
// 跨域请求允许保存cookie
axios.defaults.withCredentials = true

use([
  CanvasRenderer,
  GridComponent,
  ToolboxComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  BarChart
]);

const labelOption = {
  show: true,
  position: 'insideBottom',
  distance: 8,
  align: 'left',
  verticalAlign: 'middle',
  rotate: 90,
  formatter: '{c} {name|{a}}',
  fontSize: 16,
  rich: {
    name: {}
  }
};

export default {
  name: "BarChart",
  components: {
    VChart
  },
  data() {
    return {
      option: {},
      scaleList: [],
      total: 0,
      pageSize: 1,
      pageIndex: 1,
    };
  },
  methods: {
    loadBarChart() {
      let appkey = "com.sankuai.seawater.server,com.sankuai.waimai.c.address";
      let cell = "";
      axios({
        method: "get",
        url: "/sea/api/scaling/barList",
        params: {
          appkey: appkey,
          cellName: cell
        },
      }).then((res) => {
        let barResult = res.data;
        let x2DataMap = new Map()
        barResult.data.forEach(item => {
          let arr = item['orgDisplayName'].split('/')
          let x2Name = arr[3]
          if (x2Name) {
            let x2 = x2DataMap.get(x2Name)
            if (x2) {
              //console.log(x2)
            } else {
              x2 = { "name": x2Name, "c1": 0, "c2": 0 }
            }
            x2.c1 += item.v1
            x2.c2 += item.v2 + item.v3 + item.v4
            x2DataMap.set(x2Name, x2)
          }
        })
        const x2Data = Array.from(x2DataMap.values())
        let title
        if (cell === ' ' || cell === '') {
          title = '各业务中心弹性配置巡检'
        } else {
          title = '各业务中心弹性配置巡检[' + cell + ']'
        }
        this.option = {
          title: {
            text: title,
            left: 'center'
          },
          xAxis: [
            {
              type: 'category',
              axisTick: { show: false },
              data: x2Data.map(item => item.name)
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '弹性配置数量',
              axisLabel: {
                formatter: '{value}'
              }
            }
          ],
          legend: {
            top: 'bottom',
            left: 'center',
            data: ['配置有效', '配置无效']
          },
          series: [
            {
              name: '配置有效',
              type: 'bar',
              label: labelOption,
              yAxisIndex: 0,
              itemStyle: {
                color: '#425066' //黛色
              },
              tooltip: {
                valueFormatter: function (value) {
                  return value
                }
              },
              data: x2Data.map(item => item.c1)
            },
            {
              name: '配置无效',
              type: 'bar',
              label: labelOption,
              yAxisIndex: 0,
              tooltip: {
                valueFormatter: function (value) {
                  return value
                }
              },
              itemStyle: {
                color: '#896c39' //秋色
              },
              data: x2Data.map(item => item.c2)
            }
          ],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999'
              }
            }
          },
          toolbox: {
            show: true,
            orient: 'vertical',
            left: 'right',
            top: 'center',
            feature: {
              mark: { show: true },
              dataView: { show: true, readOnly: false },
              magicType: { show: true, type: ['line', 'bar', 'stack'] },
              restore: { show: true },
              saveAsImage: { show: true }
            }
          }
        }
      });
    },
    loadTable() {
      let appkey = "com.sankuai.seawater.server,com.sankuai.waimai.c.address";
      let cell = "";
      axios({
        method: "get",
        url: "/sea/api/scaling/list",
        params: {
          appkey: appkey,
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          cellName: cell
        },
      }).then((res) => {
        let barResult = res.data;
        this.scaleList = this.dataTransform(barResult.data);

        axios({
          method: "get",
          url: "/sea/api/scaling/listCount",
          params: {
            appkey: appkey,
            cellName: cell
          },
        }).then(res => {
          let result = res.data
          this.total = result.data;
        })
      });
    },
    dataTransform(data) {
      let length = data.length
      for (let i = 0, len = length; i < len; i++) {
        let row = data[i]
        let rawCell = row['cell']
        if (rawCell === '') {
          data[i]['cell'] = '默认'
        }
        let quotaStatus = row['quotaStatus']
        let scaleStatus = row['scaleStatus']
        let strategyStatus = row['strategyStatus']

        if (scaleStatus == 1) {
          if (strategyStatus == 1) {
            if (quotaStatus == 1) {
              data[i]['status'] = '是'
            } else {
              data[i]['status'] = '否'
              data[i]['description'] = '弹性资源不足'
            }
          } else {
            data[i]['status'] = '否'
            data[i]['description'] = '缺少弹性任务'
          }
        } else {
          data[i]['status'] = '否'
          data[i]['description'] = '缺少弹性配置'
        }
      }
      //console.log("data:" + JSON.stringify(data))
      return data
    },
    gotoHulk(appkey) {
      let url = 'https://as.mws.sankuai.com/avatar-hulk-new/group-new?env=prod&appkey=' + appkey
      window.open(url)
    },
    doPagination: function (currentPage) {
      this.pageIndex = currentPage;
      this.loadTable()
    }
  },
  mounted() {
    this.loadBarChart()
    this.loadTable()
  }
};
</script>

<style scoped>
.chart {
  height: 400px;
}

.strategy-table-expand {
  margin-left: 40px;
  margin-right: 0;
  margin-bottom: 0;
  width: 70%;
}
</style>